// Jquery timer plugin
jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;

			if (jQuery.isFunction(label)) {
				if (!times)
					times = fn;
				fn = label;
				label = interval;
			}

			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}

			times = times || 0;
			belay = belay || false;

			if (!element.$timers)
				element.$timers = {};

			if (!element.$timers[label])
				element.$timers[label] = {};

			fn.$timerID = fn.$timerID || this.guid++;

			var handler = function() {
				if (belay && this.inProgress)
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};

			handler.$timerID = fn.$timerID;

			if (!element.$timers[label][fn.$timerID])
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);

			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );

		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;

			if ( timers ) {

				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}

					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}

				for ( ret in timers ) break;
				if ( !ret )
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});
// End of Jquery timer plugin ------------------------------------------------

$(function() {

	var setDescHeight = function() {
		var h = new Array();
		var t = 0;
		$('#wizard-container td .level .desc').each(function() {
			h.push($(this).height());
		});
		for (var i = 0; i < h.length; i++) {
			t = (h[i] > t) ? h[i] : t;
		}
		$('#wizard-container td .level .desc').height(t);
	};

	$(window).load(setDescHeight);

	var mOver = function(e) {
//		mOut();
		var elm = $(this);
		elm.find('div.desc').height('auto');
		elm.find('div.icon').addClass('icon-hovered');
		elm.find('div.details').show();
	};

	var mOut = function(e) {
		$('#wizard-container div.icon').removeClass('icon-hovered');
		$('#wizard-container div.details').hide();
		setDescHeight();
	};

	var moreClick = function(e) {
		$(this).parents('div.level').unbind('mouseleave', mOut);
		var id = $(this).parents('div.level').attr('id');
		popupShow('t-' + id);
	};

	$('#wizard-container div.level').bind('mouseover', mOver).bind('mouseleave', mOut).find('.details a').bind('click', moreClick);
	$('#wizard-container div.level').find('div.icon').bind('click', function() {
		$(this).next(0).find('.details a').trigger('click');
	});

	var popupShow = function(e) {
		$('#t-level-overlay').show();
		position('#'+e);
		$('#'+e).addClass('t-level-active').show();
		disabling();
	};

	var popupRedirectOpen = function(elm) {
		$('div.t-level-active').removeClass('t-level-active').hide();
		var id = $(this).parents('div.t-level').attr('id');
		$('#' + id + '-ok').addClass('t-level-active').show();
		position('.t-level-active');
	};

	var popupClose = function(e) {
		$('.t-level-active').removeClass('t-level-active').hide();
		$('#t-level-overlay').hide();
		$('div.level').bind('mouseleave', mOut);
		mOut();
		$('.error-desc, .ok-desc').hide();
	}

	// Positioning popup
	var position = function(e) {
		var w = $(e).width();
		var h = $(e).height();
		var setPos = function() {
			$(e).css({
				top: ($(window).height() - h) / 2,
				left: ($(window).width() - w) / 2,
				position: 'fixed'
			});
			if ($.browser.msie && $.browser.version.number < 7) {
				$('#t-level-overlay').css({
					width: document.documentElement.clientWidth,
					height: document.documentElement.clientHeight,
					top: 0,
					position: 'absolute'
				});
				$(e).css({
					top: (document.documentElement.clientHeight - h) / 2,
					position: 'absolute'
				});
			}
		};
		setPos();
		if ($(window).width() <= w) {
			$(e).css({
				left:0,
				position: 'absolute'
			});
		}
		if ($(window).height() <= h) {
			$(e).css({
				top:0,
				position: 'absolute'
			});
		}
	};
	$(window).resize(function() {
		position('.t-level-active');
	});

	$('a.popup-close').click(popupClose);
	$('#t-level-overlay').click(popupClose);

	// Disabling non used blocks
	var disabling = function() {
		$('.button-activate').hide();
		$('.button-activate-disabled').show();
		if ($.browser.msie) {
			$('.button-activate-disabled').css('display', 'inline-block');
		}
		$('.site-name').removeClass('check-error').removeClass('check-ok');
	};


	var checkDomainFormat = function(domain) {
		return domain.match(/^([a-z0-9\-]+\.)+[a-z]{2,}$/ig);
	};

	var tmuaCheckDomainFormat = function(domain) {
		return domain.match(/^[a-z0-9][a-z0-9\-]{1,50}$/ig);
	};


	var tmuaCheckDomain = function() {
		var domainUrlInput = $('#site-name-input');
		var ajaxLoader = $('#site-name-input-loader');
		var domainUrl = domainUrlInput.val();
		disabling();
		if (tmuaCheckDomainFormat(domainUrl)) {
			domainUrlInput.hide();
			ajaxLoader.show();
			$('.error-desc, .ok-desc').hide();
			var d_URL = domainUrl;
			$.ajax({
				async    : true,
				type     : "GET",
				url      : "/a_ajax/wizard.isSubDomainAvailable",
				dataType : "text",
				data     : "domainUrl=" + d_URL,
				success: function(data){
					ajaxLoader.hide();
					domainUrlInput.show();
					if (data == 1) {
						$('.site-name').removeClass('check-error').addClass('check-ok');
						$('.button-activate-disabled').hide();
						$('.button-activate').show().focus();
						if ($.browser.msie) {
							$('.button-activate').css('display', 'inline-block');
						}
						$('.button-activate').bind('click', {domainName: d_URL}, freeDomainSiteActivate);
						$('.site-name').parents('.m').find('.domain-avail').show();
					} else {
						$('.site-name').removeClass('check-ok').addClass('check-error');
						$('.site-name').parents('.m').find('.domain-busy').show();
						$('.site-name').parents('.m').find('.ok-desc').hide();
						domainUrlInput.focus();
						domainUrlInput.css({border: '2px solid #ff0000'});
					}
				}
			});

		} else {
			$('.site-name').removeClass('check-ok').addClass('check-error');
			$(this).parents('.m').find('.syntax-error').show();
			$(this).parents('.m').find('.ok-desc').hide();
			domainUrlInput.focus();
			domainUrlInput.css({border: '2px solid #ff0000'});
		}
	};

	var freeDomainSiteActivate = function(e) {
		var d_URL = e.data.domainName;
		$.ajax({
			async    : true,
			type     : "GET",
			url      : "/a_ajax/wizard.isSubDomainAvailable",
			dataType : "text",
			data     : "domainUrl=" + d_URL,
			success: function(data){
				if (data == 1) {
					$('.t-level-active').hide();
					position('#t-level-1-ok');
					$('#t-level-1-ok').show().addClass('t-level-active');
					registerFreeSubDomain(d_URL);
					$('#t-level-overlay').unbind('click', popupClose);
					$('#t-level-1-ok .popup-close').unbind('click', popupClose);
				}
			}
		});
	};

	// Starting timer
	var startTimer = function(elm) {
		elm.everyTime(1000, function(i) {
			$(this).html(10-i);
		});
	};


	var registerFreeSubDomain = function(d_URL) {
		$.ajax({
			async    : true,
			type     : "GET",
			url      : "/a_ajax/wizard.registerSubDomain",
			dataType : "json",
			data     : "domainUrl=" + d_URL,
			success: function(resp){
				var redirectText = $('#t-level-1-ok .popup-container .redirect-text');
				var redirectValue = redirectText.find('span');
				redirectText.append('<p><a href="' + resp.data.fullUrl + '">' + resp.data.displayUrl + '</a></p>');
				startTimer(redirectValue);
				setTimeout(function() {
					redirectValue.stopTime();
					location.href = resp.data.fullUrl;
				}, 10000);
			}
		});
	};

	$('#submit-site-request').click(function(){
		req = {
			'req_name'            : $('#req_site_name').val(),
			'req_has_domain'      : $('#req_site_has_domain').val(),
			'req_domain_name'     : $('#req_site_domain').val() + '.' + $('#req_site_domain_zone').val(),
			'req_phone'           : $('#req_site_phone').val(),
			'req_call_start_time' : $('#req_site_call_start_time').val(),
			'req_call_end_time'   : $('#req_site_call_end_time').val()
		};
		$.post("/a_ajax/wizard.registerSite", req, registerSiteCallback, "json");
		function registerSiteCallback(resp, textStatus) {
			if (resp.error) {
				alert(resp.error);
			}
			else {
				$('#t-level-2-ok span.userName').text($('#req_site_name').val());
				$('.t-level-active').hide();
				position('#t-level-2-ok');
				$('#t-level-2-ok').show().addClass('t-level-active');
				var redirectValue = $('#t-level-2-ok .popup-container .redirect-text span');
				startTimer(redirectValue);
				setTimeout(function() {
					redirectValue.stopTime();
					location.href = resp.data.redirectLink;
				}, 10000);
				$('#t-level-overlay').unbind('click', popupClose);
				$('#t-level-2-ok .popup-close').unbind('click', popupClose);
			}
		}
	});

	$('#submit-site-support-request').click(function(){
		req = {
			'req_name'            : $('#req_site_sup_name').val(),
			'req_has_domain'      : $('#req_site_sup_has_domain').val(),
			'req_domain_name'     : $('#req_site_sup_domain').val() + '.' + $('#req_site_sup_domain_zone').val(),
			'req_phone'           : $('#req_site_sup_phone').val(),
			'req_call_start_time' : $('#req_site_sup_call_start_time').val(),
			'req_call_end_time'   : $('#req_site_sup_call_end_time').val()
		};
		$.post("/a_ajax/wizard.registerSiteSupport", req, registerSiteCallback, "json");
		function registerSiteCallback(resp, textStatus) {
			if (resp.error) {
				alert(resp.error);
			}
			else {
				$('#t-level-3-ok span.userName').text($('#req_site_sup_name').val());
				$('.t-level-active').hide();
				position('#t-level-3-ok');
				$('#t-level-3-ok').show().addClass('t-level-active');
				var redirectValue = $('#t-level-3-ok .popup-container .redirect-text span');
				startTimer(redirectValue);
				setTimeout(function() {
					redirectValue.stopTime();
					location.href = resp.data.redirectLink;
				}, 10000);
				$('#t-level-overlay').unbind('click', popupClose);
				$('#t-level-3-ok .popup-close').unbind('click', popupClose);
			}
		}
	});

	// Level 1 activating
	$('#t-level-1 .controls a.button-check').bind('click', tmuaCheckDomain);
	$('#t-level-1 #site-name-input').keydown(function(event) {
		$(this).parents('.site-name').removeClass('check-error check-ok').siblings('.error-desc, .ok-desc').hide();
		$(this).css({border: '1px solid #DDAC7B'});
		if (event.keyCode == 13) {
			$('#t-level-1 .controls a.button-check').trigger('click');
		}
	});


});